package com.lry.basic.algorithm.stack;

import java.util.ArrayList;
import java.util.List;
import java.util.Stack;

/**
 * @author:刘仁有
 * @desc:
 * @email:953506233@qq.com
 * @data:2019/12/3
 */
public class DecodeStr {
    //    3[a2[c]]  a2[c]a2[c]a2[c]

    public static void main(String[] args) {
        System.out.println(DecodeStr.decodeString("13[a2[cd]]"));
    }
    public static String decodeString(String s) {
        if(null==s)return null;
        Stack<Character>stack = new Stack<>();
        for(int i=0;i<s.length();i++){
            char c = s.charAt(i);
            if(c==']'){
                List<Character> strs = new ArrayList<>();
                while(!stack.isEmpty()&&stack.peek()!='[') {
                    strs.add(stack.pop());//d c
                }
                if(!stack.isEmpty())
                stack.pop();//弹出[
                List<Integer> nums = new ArrayList<>();
                while(!stack.isEmpty()&&stack.peek()-48>=0&&stack.peek()-48<=9){
                    nums.add(stack.pop()-48);
                }
                //重复次数
                int count = 0;
                for(int j=0;j<nums.size();j++){
                    count += nums.get(j)*Math.pow(10,j);
                }

                for(int j=0;j<count;j++) {
                    for (int k = strs.size() - 1; k >= 0; k--) {
                        stack.push(strs.get(k));
                    }
                }
            }else{
                stack.push(s.charAt(i));
            }
        }
        StringBuilder sb = new StringBuilder();
        for (Character c:stack) {
            sb.append(c);
        }
        return sb.toString();
    }
}
